﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using Newtonsoft.Json;
using OnWork.DataCenter.BLL.Standard;
using OnWork.DataCenter.DAL.DataCenter;
using OnWork.DataCenter.Utils;

namespace OnWork.DataCenter.Shared.Pages.DataStandard
{
    public partial class DataStandardConfigEditView : ComponentBaseDataCenter, IResultDialog
    {
        /// <summary>
        /// 传入的配置文件
        /// </summary>
        //[CascadingParameter(Name = "BodyContext")]
        [Parameter]
        public DataStandardConfigVO? Config { get; set; }

        /// <summary>
        /// 解析结果
        /// </summary>
        private string Result { get; set; }

        /// <summary>
        /// 测试按钮点击时
        /// </summary>
        /// <returns></returns>

        private async Task OnClickTestAsync()
        {
            try
            {
                if (Config.DataType == DataStandardType.Json && Config.OutType == DataStandardType.DataTable)
                {
                    var table = StandardConvert.JsonToDataTable(Config.DataDemo, JsonConvert.DeserializeObject<JsonToDataTableConfig>(Config.StandardConfig));
                    Result = StandardConvert.DataTableToJson(table);
                }
                else if (Config.DataType == DataStandardType.DataTable && Config.OutType == DataStandardType.DataBase)
                {
                    var dt = StandardConvert.JsonToDataTable(Config.DataDemo);
                    var icount = StandardConvert.DataTableToDataBase(dt, JsonConvert.DeserializeObject<DataTableToDBConfig>(Config.StandardConfig));
                    Result = $"数据库插入数据{icount}条";
                    //Result = StandardConvert.(table);
                }
                else if (Config.DataType == DataStandardType.DataBase && Config.OutType == DataStandardType.DataTable)
                {
                    var table = await StandardConvert.DataBaseToDataTableAsync(JsonConvert.DeserializeObject<DBToDataTableConfig>(Config.StandardConfig));
                    Result = StandardConvert.DataTableToJson(table);
                }
                else if (Config.DataType == DataStandardType.DataTable && Config.OutType == DataStandardType.Json)
                {
                    var dt = StandardConvert.JsonToDataTable(Config.DataDemo);
                    Result = StandardConvert.DataTableToJsonWithConfig(dt, JsonConvert.DeserializeObject<DataTableToJsonConfig>(Config.StandardConfig));
                }
                else if (Config.DataType == DataStandardType.Json && Config.OutType == DataStandardType.Mqtt)
                {
                    var config = JsonConvert.DeserializeObject<JsonToMqttConfig>(Config.StandardConfig);
                    StandardConvert.JsonToMqtt(Config.DataDemo, config);
                    Result = $"消息已发送请订阅{config.Topic}查看!";
                }
                else if (Config.DataType == DataStandardType.Json && Config.OutType == DataStandardType.Variables)
                {
                    var config = JsonConvert.DeserializeObject<JsonToVariablesConfig>(Config.StandardConfig);
                    var result = StandardConvert.JsonToVariables(Config.DataDemo, config);
                    Result = JsonHelper.SerializeFormat(result);
                }
                else if (Config.DataType == DataStandardType.Http && Config.OutType == DataStandardType.Json)
                {
                    var config = JsonConvert.DeserializeObject<HttpToJsonConfig>(Config.StandardConfig);
                    var re = await StandardConvert.HttpToJsonAsync(config);
                    if (re.IsNotEmptyOnWork())
                    {
                        Result = JsonHelper.JsonFormatOnWork(re);//json格式化
                    }
                }
                else if (Config.DataType == DataStandardType.Exe && Config.OutType == DataStandardType.Exe) //执行exe
                {
                    var config = JsonConvert.DeserializeObject<ExeToExeConfig>(Config.StandardConfig);
                    var re = await StandardConvert.ExeToExeAsync(config);
                    Result = $"已经执行{config.FileName}程序!";
                }
                else
                {
                    var msg = $"暂未实现{Config.DataType}到{Config.OutType}功能!";
                    await base.MessageError(msg);
                }
            }
            catch (Exception ex)
            {
                await base.MessageError(ex.ToString());
            }
        }

        //// <summary>
        /// 编辑配置按钮
        /// </summary>
        /// <returns></returns>
        private async Task OnClickConfigAsync()
        {
            //json转DateTable
            if (Config.DataType == DataStandardType.Json && Config.OutType == DataStandardType.DataTable)
            {
                await JsonToDataTableConfigAsync();
            }
            else if (Config.DataType == DataStandardType.DataTable && Config.OutType == DataStandardType.DataBase)
            {
                await DataTableToDBAsync();
            }
            else if (Config.DataType == DataStandardType.DataBase && Config.OutType == DataStandardType.DataTable)
            {
                await DBToDataTableAsync();
            }
            else if (Config.DataType == DataStandardType.DataTable && Config.OutType == DataStandardType.Json)
            {
                await DataTableToJsonAsync();
            }
            else if (Config.DataType == DataStandardType.Json && Config.OutType == DataStandardType.Mqtt)
            {
                await JsonToMqttAsync();
            }
            else if (Config.DataType == DataStandardType.Json && Config.OutType == DataStandardType.Variables)
            {
                await JsonToVariablesConfigAsync();
            }
            else if (Config.DataType == DataStandardType.Http && Config.OutType == DataStandardType.Json)
            {
                await HttpToJsonAsync();
            }
            else if (Config.DataType == DataStandardType.Exe && Config.OutType == DataStandardType.Exe)
            {
                await ExeToExeConfigAsync();
            }
            else
            {
                var msg = $"暂未实现{Config.DataType}到{Config.OutType}功能!";
                await base.MessageError(msg);
            }
        }

        /// <summary>
        /// Json转MQTT
        /// </summary>
        /// <returns></returns>
        private async Task HttpToJsonAsync()
        {
            var con = new BLL.Standard.HttpToJsonConfig() { };

            try
            {
                var obj = JsonHelper.Deserialize<HttpToJsonConfig>(Config.StandardConfig);

                //var obj = System.Text.Json.JsonSerializer.Deserialize<HttpToJsonConfig>(Config.StandardConfig);
                if (obj != null)
                {
                    con = obj;
                }
            }
            catch (Exception)
            {
            }

            var op = new DialogOption()
            {
                Title = "配置编辑",
                ShowFooter = false,
                BodyContext = con
            };

            op.Component = BootstrapDynamicComponent.CreateComponent<HttpToJsonConfigView>(new Dictionary<string, object?>
            {
                [nameof(HttpToJsonConfigView.OnSave)] = new Action<HttpToJsonConfig>(x =>
                {
                    if (Config != null)
                        Config.StandardConfig = JsonHelper.SerializeFormat(x);//jsonToDataTableConfig.
                })
            });
            //
            await base.DialogService.Show(op);
        }

        /// <summary>
        /// Json转MQTT
        /// </summary>
        /// <returns></returns>
        private async Task JsonToMqttAsync()
        {
            var con = new BLL.Standard.JsonToMqttConfig() { };

            try
            {
                var obj = JsonConvert.DeserializeObject<JsonToMqttConfig>(Config.StandardConfig);
                if (obj != null)
                {
                    con = obj;
                }
            }
            catch (Exception)
            {
            }

            var op = new DialogOption()
            {
                Title = "配置编辑",
                ShowFooter = false,
                BodyContext = con
            };

            op.Component = BootstrapDynamicComponent.CreateComponent<JsonToMqttConfigView>(new Dictionary<string, object?>
            {
                [nameof(JsonToMqttConfigView.OnSave)] = new Action<JsonToMqttConfig>(x =>
                {
                    Config.StandardConfig = JsonConvert.SerializeObject(x, Formatting.Indented);//jsonToDataTableConfig.
                })
            });
            //
            await base.DialogService.Show(op);
        }

        /// <summary>
        /// 数据库转表格
        /// </summary>
        /// <returns></returns>
        private async Task DataTableToJsonAsync()
        {
            var con = new BLL.Standard.DataTableToJsonConfig() { Cols = new List<DataTableCol>() };

            try
            {
                var obj = JsonConvert.DeserializeObject<DataTableToJsonConfig>(Config.StandardConfig);
                if (obj != null)
                {
                    con = obj;
                }
            }
            catch (Exception)
            {
            }

            var op = new DialogOption()
            {
                Title = "配置编辑",
                ShowFooter = false,
                BodyContext = con
            };

            op.Component = BootstrapDynamicComponent.CreateComponent<DataTableToJsonConfigView>(new Dictionary<string, object?>
            {
                //[nameof(DataTableToDBConfigView.OnClose)] = new Action(async () => await op.Dialog.Close()),
                [nameof(DataTableToJsonConfigView.OnSave)] = new Action<DataTableToJsonConfig>(x =>
                {
                    //jsonToDataTableConfig = x;
                    //await op.Dialog.Close();
                    if (Config != null)
                    {
                        Config.StandardConfig = JsonConvert.SerializeObject(x, Formatting.Indented);//jsonToDataTableConfig.
                    }
                })
            });
            //
            await base.DialogService.Show(op);
        }

        /// <summary>
        /// 数据库转表格
        /// </summary>
        /// <returns></returns>
        private async Task DBToDataTableAsync()
        {
            var con = new BLL.Standard.DBToDataTableConfig() { };

            try
            {
                var obj = JsonConvert.DeserializeObject<DBToDataTableConfig>(Config.StandardConfig);
                if (obj != null)
                {
                    con = obj;
                }
            }
            catch (Exception)
            {
            }

            var op = new DialogOption()
            {
                Title = "配置编辑",
                ShowFooter = false,
                BodyContext = con
            };

            op.Component = BootstrapDynamicComponent.CreateComponent<DBToDataTableConfigView>(new Dictionary<string, object?>
            {
                //[nameof(DataTableToDBConfigView.OnClose)] = new Action(async () => await op.Dialog.Close()),
                [nameof(DBToDataTableConfigView.OnSave)] = new Action<DBToDataTableConfig>(x =>
                {
                    //jsonToDataTableConfig = x;
                    //await op.Dialog.Close();

                    if (Config != null)
                    {
                        Config.StandardConfig = JsonConvert.SerializeObject(x, Formatting.Indented);//jsonToDataTableConfig.
                    }
                })
            });
            //
            await base.DialogService.Show(op);
        }

        /// <summary>
        /// 表格转数据库
        /// </summary>
        /// <returns></returns>
        private async Task DataTableToDBAsync()
        {
            var con = new BLL.Standard.DataTableToDBConfig() { DBCols = new List<BLL.Standard.DBCol>() };

            try
            {
                var obj = JsonConvert.DeserializeObject<DataTableToDBConfig>(Config.StandardConfig);
                if (obj != null)
                {
                    con = obj;
                }
            }
            catch (Exception)
            {
            }

            var op = new DialogOption()
            {
                Title = "配置编辑",
                ShowFooter = false,
                BodyContext = con
            };

            op.Component = BootstrapDynamicComponent.CreateComponent<DataTableToDBConfigView>(new Dictionary<string, object?>
            {
                //[nameof(DataTableToDBConfigView.OnClose)] = new Action(async () => await op.Dialog.Close()),
                [nameof(DataTableToDBConfigView.OnSave)] = new Action<DataTableToDBConfig>(x =>
                {
                    //jsonToDataTableConfig = x;
                    //await op.Dialog.Close();
                    if (Config != null)
                    {
                        Config.StandardConfig = JsonConvert.SerializeObject(x, Formatting.Indented);//jsonToDataTableConfig.
                    }
                })
            });
            //
            await base.DialogService.Show(op);
        }

        /// <summary>
        /// 编辑配置
        /// </summary>
        /// <returns></returns>
        private async Task JsonToDataTableConfigAsync()
        {
            var con = new BLL.Standard.JsonToDataTableConfig() { Cols = new List<BLL.Standard.DataTableCol>() };

            try
            {
                var obj = JsonConvert.DeserializeObject<JsonToDataTableConfig>(Config.StandardConfig);
                if (obj != null)
                {
                    con = obj;
                }
            }
            catch (Exception)
            {
            }

            var op = new DialogOption()
            {
                Title = "配置编辑",
                ShowFooter = false,
                BodyContext = con
            };

            op.Component = BootstrapDynamicComponent.CreateComponent<JsonToDataTableConfigView>(new Dictionary<string, object?>
            {
                [nameof(JsonToDataTableConfigView.OnClose)] = new Action(async () => await op.CloseDialogAsync()),
                [nameof(JsonToDataTableConfigView.OnSave)] = new Action<JsonToDataTableConfig>(x =>
                {
                    //jsonToDataTableConfig = x;
                    //await op.Dialog.Close();
                    if (Config != null)
                    {
                        Config.StandardConfig = JsonConvert.SerializeObject(x, Formatting.Indented);//jsonToDataTableConfig.
                    }
                })
            });
            //
            await base.DialogService.Show(op);
        }

        /// <summary>
        /// Json转变量
        /// </summary>
        /// <returns></returns>
        private async Task JsonToVariablesConfigAsync()
        {
            var con = new BLL.Standard.JsonToVariablesConfig() { Variables = new List<BLL.Standard.VariableDto>() };
            try
            {
                var obj = JsonConvert.DeserializeObject<JsonToVariablesConfig>(Config.StandardConfig);
                if (obj != null)
                {
                    con = obj;
                }
            }
            catch (Exception)
            {
            }

            var op = new DialogOption()
            {
                Title = "配置编辑",
                ShowFooter = false,
                BodyContext = con
            };

            op.Component = BootstrapDynamicComponent.CreateComponent<JsonToVariablesConfigView>(new Dictionary<string, object?>
            {
                [nameof(JsonToVariablesConfigView.OnSave)] = new Action<JsonToVariablesConfig>(x =>
                {
                    if (Config != null)
                    {
                        Config.StandardConfig = JsonHelper.SerializeFormat(x);
                    }
                })
            });
            await base.DialogService.Show(op);
        }

        /// <summary>
        /// Exe转对象
        /// </summary>
        /// <returns></returns>
        private async Task ExeToExeConfigAsync()
        {
            var con = new BLL.Standard.ExeToExeConfig();
            try
            {
                var obj = JsonConvert.DeserializeObject<ExeToExeConfig>(Config.StandardConfig);
                if (obj != null)
                {
                    con = obj;
                }
            }
            catch (Exception)
            {
            }

            var op = new DialogOption()
            {
                Title = "配置编辑",
                ShowFooter = false,
                BodyContext = con
            };

            op.Component = BootstrapDynamicComponent.CreateComponent<ExeToExeConfigView>(new Dictionary<string, object?>
            {
                [nameof(ExeToExeConfigView.OnSave)] = new Action<ExeToExeConfig>(x =>
                {
                    if (Config != null)
                    {
                        Config.StandardConfig = JsonHelper.SerializeFormat(x);
                    }
                })
            });
            await base.DialogService.Show(op);
        }

        /// <summary>
        /// 返回关闭结果
        /// </summary>
        [Parameter]
        public Action<DataStandardConfigVO>? OnCloseResult { get; set; }

        public async Task OnClose(DialogResult result)
        {
            if (result == DialogResult.Yes)
            {
                if (OnCloseResult != null && Config != null)
                {
                    OnCloseResult(Config); //返回执行结果
                }
            }

            await Task.CompletedTask;
        }

        /// <summary>
        /// Json转DataTable配置
        /// </summary>
        //private OnWork.DataCenter.BLL.Standard.JsonToDataTableConfig jsonToDataTableConfig = new BLL.Standard.JsonToDataTableConfig() { Cols = new List<BLL.Standard.JsonToDataTableCol>() };
    }
}